package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.ExportProductService;
import cn.itcast.service.cargo.FinanceService;
import cn.itcast.service.cargo.InvoiceService;
import cn.itcast.service.cargo.PackingService;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/cargo/finance")
public class FinanceController extends BaseController {
    @Reference
    private FinanceService financeService;

    @Reference
    private ExportProductService exportProductService;

    @Reference
    private InvoiceService invoiceService;

    @Reference
    private PackingService packingService;

    /**
     * 查询财务报运单列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping("/list")
    public String financeList(/*@Param("s") String s,*/
                              @RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "5") Integer pageSize) {

        FinanceExample financeExample = new FinanceExample();
        financeExample.createCriteria().andCompanyIdEqualTo(getLoginCompanyId());
        PageInfo<Finance> pageInfo = financeService.findByPage(financeExample, pageNum, pageSize);
        request.setAttribute("pageInfo", pageInfo);
        return "cargo/finance/finance-list";
    }

    /**
     * 转到财务报运单面
     */
    @RequestMapping("/toAdd")
    public String toAdd(String id){
        // 获取发票、 装箱、数据
        //
        Invoice invoice = invoiceService.findById(id);
        Packing packing = packingService.findById(id);
        Finance finance = new Finance();
        finance.setFinanceId(id);
        finance.setInputeDate(new Date());
        finance.setInvoiceId(id);
        finance.setInvoiceMoney(invoice.getInvoiceMoney());
        finance.setInvoiceTime(invoice.getInvoiceTime());
        finance.setExportNos(packing.getExportNos());
        finance.setShipmentPort(packing.getShipmentPort());
        finance.setDestinationPort(packing.getDestinationPort());
        finance.setConsignee(packing.getConsignee());
        finance.setCreateBy(getLoginUser().getId());
        finance.setCreateDept(getLoginUser().getDeptId());
        finance.setCompanyId(getLoginCompanyId());
        finance.setCompanyName(getLoginCompanyName());
       /* finance.setFinanceId("348188d9-898b-4e52-b563-2328874dd6fb");
        finance.setInputeDate(new Date());
        finance.setInvoiceId("NO.432111");
        finance.setInvoiceTime(new Date());
        finance.setExportNos("348188d9-898b-4e52");
        finance.setShipmentPort("上海");
        finance.setDestinationPort("深圳");
        finance.setConsignee("jack");
        finance.setCreateBy("Tom");
        finance.setCompanyId("1");
        finance.setCompanyName("黑马");
        finance.setCreateDept("开发部");
        finance.setInvoiceMoney(11.9);*/
        request.setAttribute("finance",finance);
        return "cargo/finance/finance-add";
    }

    /**
     * 保存 财务报运单
     * @param finance
     * @return
     */
    @RequestMapping("/save")
    public String save(Finance finance){
       /* String a="aaa";*/
        financeService.save(finance);
        return "redirect:/cargo/finance/list";
    }



    /**
     * 跳转到查看页面
     */
    @GetMapping("/toView")
    public String toView(String id) {
        Finance finance = financeService.findById(id);
        request.setAttribute("finance", finance);
        return "cargo/finance/finance-view";
    }

    @RequestMapping("/toXlsx")
    public void toXlsx(String id) throws Exception {
        //【读取excel模板】
        InputStream in =
                session.getServletContext()
                        .getResourceAsStream("/make/xlsprint/finance_mb.xlsx");
        //【根据excel模板文件流，创建工作簿】
        Workbook workbook = new XSSFWorkbook(in);
        //【获取工作表】
        Sheet sheet = workbook.getSheetAt(0);

        Finance finance = financeService.findById(id);
        //这里从获取报运单
        List<String> exportIds = new ArrayList<String>();
        exportIds.add("74cc449a-5c18-48fe-8415-257f9cb4f035");  // 虚拟数据
        exportIds.add("74cc449a-5c18-48fe-8415-257f9cb4f035");

        ExportProductExample example = new ExportProductExample();
        ExportProductExample.Criteria criteria = example.createCriteria();
        criteria.andExportIdIn(exportIds);
        List<ExportProduct> exportProductList = exportProductService.findAll(example);

        Integer numCounts = 0;       // 总数量
        Integer boxCounts = 0;       // 总件数
        Double grossWeightCounts = 0.0; //总毛重
        Double netWeightCounts = 0.0;   //总净重
        Double ckMoneyCounts = 0.0;     // 出口总金额
        Double sgMoneyCounts = 0.0;     // 收购总金额
        Double sjCounts = 0.0;          // 总税金
        Double sizeCounts = 0.0;      // 总体积

        Integer rowNum = 7;   // 数据行开始
        if (exportProductList.size() > 0) {
            for (int i = 0; i < exportProductList.size(); i++) {
                ExportProduct eps = exportProductList.get(i);
                Row row = sheet.getRow(rowNum++);
                Integer cellNum = 0;
                Cell cell = row.getCell(0);
                cell.setCellValue(eps.getProductNo());
                cellNum++;
                cell = row.getCell(2);
                cell.setCellValue(eps.getFactoryId());
                cell = row.getCell(3);
                cell.setCellValue(eps.getPackingUnit());
                cell = row.getCell(4);
                cell.setCellValue(eps.getCnumber());
                cell = row.getCell(5);
                cell.setCellValue(eps.getBoxNum());
                cell = row.getCell(6);
                cell.setCellValue(eps.getGrossWeight());
                cell = row.getCell(7);
                cell.setCellValue(eps.getNetWeight());
                cell = row.getCell(8);
                cell.setCellValue(eps.getSizeLength());
                cell = row.getCell(9);
                cell.setCellValue(eps.getSizeWidth());
                cell = row.getCell(10);
                cell.setCellValue(eps.getSizeHeight());
                cell = row.getCell(11);
                cell.setCellValue(eps.getExPrice());

                cell = row.getCell(12);
                // 出口金额
                Double ckje = 0.0;
                if (eps.getCnumber() != null && eps.getExPrice() != null) {
                    ckje = eps.getCnumber() * eps.getExPrice();
                }
                cell.setCellValue(ckje);// 出口金额

                cell = row.getCell(13);
                cell.setCellValue(eps.getPrice());

                // 收购金额
                Double sgje = 0.0;
                if (eps.getCnumber() != null && eps.getPrice() != null) {
                    sgje = eps.getCnumber() * eps.getPrice();
                }
                cell = row.getCell(14);
                cell.setCellValue(sgje);   // 收购金额

                cell = row.getCell(15);
                if (eps.getTax()!=null) {
                    cell.setCellValue(eps.getTax());    // 税金
                }

                numCounts += eps.getCnumber();       // 总数量
                boxCounts += eps.getBoxNum();        // 总件数
                grossWeightCounts += eps.getGrossWeight(); //总毛重
                netWeightCounts += eps.getGrossWeight();   //总净重
                ckMoneyCounts += ckje;     // 出口总金额
                sgMoneyCounts += sgje;     // 收购总金额
                sjCounts = eps.getTax();          // 总税金
                sizeCounts = eps.getSizeLength() * eps.getSizeWidth() * eps.getSizeHeight();      // 总体积
            }

            Cell cell = sheet.getRow(22).getCell(4);
            cell.setCellValue(numCounts);  // 总数量

            cell = sheet.getRow(22).getCell(5);
            cell.setCellValue(boxCounts);  // 总件数

            cell = sheet.getRow(22).getCell(6);
            cell.setCellValue(grossWeightCounts);  // 总毛重

            cell = sheet.getRow(22).getCell(7);
            cell.setCellValue(netWeightCounts);  // 总净重

            cell = sheet.getRow(22).getCell(8);
            cell.setCellValue(sizeCounts);  // 体积

            cell = sheet.getRow(22).getCell(12);
            cell.setCellValue(ckMoneyCounts);  // 出口金额

            cell = sheet.getRow(22).getCell(14);
            cell.setCellValue(sgMoneyCounts);  // 收购金额

            cell = sheet.getRow(22).getCell(15);
            cell.setCellValue(sjCounts);  // 税金

            //表头
            cell = sheet.getRow(1).getCell(2);
            cell.setCellValue(new Date());  // 制单日期

            //?
            cell = sheet.getRow(1).getCell(12);
            if (finance.getInvoiceId()!=null) {
                cell.setCellValue(finance.getInvoiceId());  // 发票号
            }

            String s = finance.getExportNos();
            cell = sheet.getRow(2).getCell(2);
            if (finance.getExportNos()!=null) {
                cell.setCellValue(finance.getExportNos());  // 合同号/确认书号
            }

            cell = sheet.getRow(3).getCell(2);
            if (finance.getConsignee()!=null) {
                cell.setCellValue(finance.getConsignee());  // 收货人及地址
            }

            cell = sheet.getRow(4).getCell(1);
            if (finance.getShipmentPort()!=null) {
                cell.setCellValue(finance.getShipmentPort());  // 装运港
            }

            cell = sheet.getRow(2).getCell(2);
            if (finance.getExportNos()!=null) {
                cell.setCellValue(finance.getExportNos());  // 合同号/确认书号
            }

            cell = sheet.getRow(4).getCell(4);
            if (finance.getDestinationPort()!=null) {
                cell.setCellValue(finance.getDestinationPort());  // 目的港
            }

            cell = sheet.getRow(23).getCell(13);
            if (finance.getCreateBy()!=null) {
                cell.setCellValue(finance.getCreateBy());  // 制单人
            }

        }

        //导出下载
        response.setHeader("content-disposition", "attachment;fileName=finance_mb.xlsx");
        OutputStream out = response.getOutputStream();
        workbook.write(out);
        workbook.close();
        out.close();
    }
}
